#include "utils.h"

float CV_GetAudioClockUs(void) {
  static float audio_clock_us = (float)0;

  if (audio_clock_us == (float)0) {
#if !defined(ENV_IS_PACE_LINUX)
    uint32_t freq, ret;

    ret = schdr_get_audio_tick(&freq);
    if (ret == 0U) {
      audio_clock_us = (float)freq;
      audio_clock_us = audio_clock_us / (float)1000000;
    } else {
      audio_clock_us = (float)12.288;
      // AmbaPrint_PrintUInt5("[WARNING] AmbaCV_Flexidag : get_audio_clock fail
      // ret = 0x%x ", ret, 0U, 0U, 0U, 0U);
    }
#else
    audio_clock_us = (float)12.288;
#endif
  }

  return audio_clock_us;
}

uint32_t CV_FlexidagTimestamp(void) {
  uint32_t val;
  float fltmp;

  fltmp = (float)cvtask_get_timestamp();
  fltmp = (float)(fltmp / CV_GetAudioClockUs());
  val = (uint32_t)fltmp;

  return val;
}

uint32_t Do_Load_And_Open_FlexidagBin(const char flexidag_path[],
                                      flexidag_memblk_t *bin_buf,
                                      AMBA_CV_FLEXIDAG_HANDLE_s *handle) {
  printf("Loading flexidag from : %s\n", flexidag_path);
  uint32_t size_align;
  uint32_t Rval = 0U;

  Rval = AmbaCV_UtilityFileSize(flexidag_path, &size_align);
  if (Rval == 0U) {
    Rval = AmbaCV_UtilityCmaMemAlloc(size_align, 1, bin_buf);
    if (Rval == 0U) {
      Rval = AmbaCV_UtilityFileLoad(flexidag_path, bin_buf);
    }
  }
  if (Rval != 0U) {
    printf("Load FlexidagBin failed (0x%x)\n", Rval);
    return Rval;
  }

  Rval = AmbaCV_FlexidagOpen(bin_buf, handle);
  if (Rval != 0U) {
    printf("Open FlexidagBin failed (0x%x)\n", Rval);
    return Rval;
  }

  return Rval;
}

uint32_t Do_Init_Flexidag(AMBA_CV_FLEXIDAG_HANDLE_s *handle,
                          AMBA_CV_FLEXIDAG_INIT_s *init) {
  uint32_t Rval = 0U;
  Rval = AmbaCV_UtilityCmaMemAlloc(handle->mem_req.flexidag_state_buffer_size,
                                   1U, &init->state_buf);
  if (Rval != 0U) {
    printf("Alloc state buffer failed (0x%x)\n", Rval);
    return Rval;
  }
  printf("------------Do_Init_Flexidag AmbaCV_UtilityCmaMemAlloc success...\n");
  printf("mem_req.flexidag_temp_buffer_size = %d \n", handle->mem_req.flexidag_temp_buffer_size);
  if (handle->mem_req.flexidag_temp_buffer_size > 0) {
    Rval = AmbaCV_UtilityCmaMemAlloc(handle->mem_req.flexidag_temp_buffer_size,
                                     1U, &init->temp_buf);
    if (Rval != 0U) {
      printf("Alloc temp buffer failed (0x%x)\n", Rval);
      return Rval;
    }
  }
  printf("------------Do_Init_Flexidag flexidag_temp_buffer_size success...\n");

  Rval = AmbaCV_FlexidagInit(handle, init);
  if (Rval != 0U) {
    printf("Flexidag init failed (0x%x)\n", Rval);
    return Rval;
  }
  printf("------------Do_Init_Flexidag AmbaCV_FlexidagInit success...\n");

  return Rval;
}